/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cz.tpj.database.ip_adresy;

import cz.tpj.util.ErrorDatabase;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import cz.tpj.database.DatabaseConnector;

/**
 * Trieda sprostredkuvava metody pre vyberanie ip adries z databazy 
 * @author jabo
 */

public class Table_ip {

    public static final String ID = "id";
    public static final String IP = "ip";
    public static final String TABLE = "ip_adresy";

    private static Table_ip im = null;
    private Connection con;
    private Statement stmt = null;

    /**
     * Vrací jedinou instanci této třídy.
     * @return Table_ip
     */
    
    public static Table_ip getInstance(){
        if(im == null){
            im = new Table_ip();
        }
        return im;
    }
    //=======================metody-------------------------
    private void databaseConnect() throws SQLException{
        DatabaseConnector dc = DatabaseConnector.getInstance();
        con = dc.getConnection();
        stmt = con.createStatement();
    }
    //--------------------------------------------------------------------------
    
    /**
     * Vrati Ip adresu na zaklade zadanej ip adresy vo formate 
     * xxx.xxx.xxx.xxx alebo xxx.xxx.xxx.xxx.xxx.xxx, kde xxx je 
     * cislo od 0 po 255.
     * @return Ip
     */

    public Ip findIpAddress(String ip_looked) throws ErrorDatabase{
        ResultSet rs = null;
        Ip score = null;
        try {
            databaseConnect();
            rs = stmt.executeQuery("SELECT * FROM "+TABLE+" WHERE "+IP+" = '"+ip_looked+"'");
            con.commit();
            String id, ip;
            if(rs.next()){
                id = rs.getString(ID);
                ip = rs.getString(IP);
                score = new Ip(id, ip);
            }
        } catch (ErrorDatabase ex) {
            throw new ErrorDatabase(ErrorDatabase.INVALID_DATA_FORMAT, "V databzí byla nalezena nekonzistentvní data.");
        } catch (SQLException ex) {
            throw new ErrorDatabase(ErrorDatabase.ERROR_DATABASE_CONECTION, "Chyba při načítání dat z databáze.");
        } finally{
            try {
                rs.close();
                stmt.close();
            } catch (Exception ex) {
            }
        }
        return score;
    }


}
